import React, { forwardRef, useEffect, useImperativeHandle } from 'react';
import { Button, DatePicker, Space } from 'antd';
import { TjSelect, TjSegmented, useTRState } from '@/pages/ETrade/components';
import moment from 'moment/moment';
import { UploadOutlined } from '#/utils/antdIcons';
import { SEARCH_TYPE } from '@/pages/GanSuDaTang/Report/DayTransaction/helper';

const { RangePicker } = DatePicker;

const defaultForm = (stations) => {
  // 默认表单
  return {
    date: moment(),
    stationIdList: stations.map(({ value }) => value),
  };
};
export const HeaderSearch = (
  { stations = [], setFatherState = Function, searchType, onExport, fetchData },
  ref,
) => {
  const [state, setState] = useTRState({
    ...defaultForm(stations),
  });

  useEffect(() => {
    moment.updateLocale('zh-cn', {
      week: { dow: 5, doy: 4 },
    });
  }, []);

  useEffect(() => {
    fetchData(state.date, state.stationIdList).then();
  }, [searchType]);

  const changeDate = (v) => {
    setState({ date: v });
  };

  const onFinish = async () => {
    await fetchData(state.date, state.stationIdList);
  };

  const onReset = () => {
    setState({
      ...defaultForm(stations),
    });
    setFatherState({
      searchType: SEARCH_TYPE[0]['value'],
    });
  };

  const changeSearchType = (v) => {
    setFatherState({ searchType: v });
  };

  const _getDateSelectEl = (v) => {
    switch (v) {
      case 0:
        return (
          <DatePicker
            style={{ width: 300 }}
            value={state.date}
            format={'YYYYMMDD'}
            allowClear={false}
            onChange={changeDate}
          />
        );
      case 1:
        return (
          <DatePicker
            style={{ width: 300 }}
            value={state.date}
            onChange={changeDate}
            picker="week"
          />
        );
      case 2:
        return (
          <DatePicker
            style={{ width: 300 }}
            value={state.date}
            onChange={changeDate}
            picker="month"
          />
        );
    }
  };

  return (
    <>
      <Space size={16} wrap>
        <TjSelect
          style={{ width: 200 }}
          value={state.stationIdList}
          options={stations}
          showSearch
          onChange={(stationIdList) => setState({ stationIdList })}
          mode="multiple"
          label="交易单元"
        />
        <TjSegmented value={searchType} onChange={changeSearchType} options={SEARCH_TYPE} />
        {_getDateSelectEl(searchType)}
        <Space size={16}>
          <Button style={{ width: 98, height: 32 }} type="primary" onClick={onFinish}>
            查询
          </Button>
          <Button style={{ width: 98, height: 32 }} ghost onClick={onReset}>
            重置
          </Button>
        </Space>
      </Space>
      <Space>
        <Button type="link" icon={<UploadOutlined />} onClick={onExport}>
          导出
        </Button>
      </Space>
    </>
  );
};
